package com.block.match.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.block.common.constant.AppRspCodeConstant;
import com.block.common.constant.RedisKeyConstant;
import com.block.common.service.LogFactory;
import com.block.common.vo.ResponseVo;
import com.block.db.entity.DataMatchOrderInfo;
import com.block.db.entity.DataMatchOrderItem;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.mapper.DataMatchOrderItemMapper;
import com.block.db.mapper.MemberSourceInfoMapper;
import com.block.db.mapper.MerchantBaseInfoMapper;
import com.block.match.enums.OrderStatusEnum;
import com.block.match.model.vo.MatchResultVO;
import com.block.match.service.IDataMatchOrderInfoService;
import com.block.match.service.IMatchApiBHandlerService;
import com.block.merchant.model.result.DataMatchResult;
import com.block.merchant.model.vo.MerchantAbiBDataPushInfoVO;
import com.block.merchant.service.IDataMerchantPushService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class MatchApiBHandlerServiceImpl implements IMatchApiBHandlerService {

    private static final Logger log = LogFactory.getCommLog();

    @Resource
    MemberSourceInfoMapper memberSourceInfoMapper;
    @Autowired
    IDataMatchOrderInfoService dataMatchOrderInfoService;
    @Resource
    DataMatchOrderItemMapper dataMatchOrderItemMapper;
    @Autowired
    IDataMerchantPushService dataMerchantPushService;
    @Resource
    MerchantBaseInfoMapper merchantBaseInfoMapper;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    @Async
    public void getApiBMatchResult(Long uid){

        try {

            MemberSourceInfo memberSourceInfo = memberSourceInfoMapper.getEntityByUidLock(Long.valueOf(uid));
            if (ObjectUtil.isEmpty(memberSourceInfo)) {
//            return new ResponseVo(AppRspCodeConstant.SYS_EXCEPTION, "用户信息为空",null);
                return;
            }

            DataMatchOrderInfo dataMatchOrderInfo = dataMatchOrderInfoService.initMatchOrderInfo(memberSourceInfo);
            MatchResultVO matchResultVO = new MatchResultVO();
            matchResultVO.setOrderId(String.valueOf(dataMatchOrderInfo.getId()));

            // 条件过滤
            DataMatchResult dataMatchResult = dataMerchantPushService.dataMatchApiBHandle(memberSourceInfo);
            if (dataMatchResult.getMatchSize() == 0) {

                matchResultVO.setMatchSuccess(false);

                DataMatchOrderInfo updateOrder = new DataMatchOrderInfo();
                updateOrder.setId(dataMatchOrderInfo.getId());
                updateOrder.setStatus(OrderStatusEnum.FAILED.getValue());
                updateOrder.setMessage("没有匹配到合适的商户信息");
                dataMatchOrderInfoService.updateById(updateOrder);

                log.info("【客户信息匹配】匹配完成，没有匹配到合适的商户【orderId】{}", dataMatchOrderInfo.getId());
//            return new ResponseVo(AppRspCodeConstant.SYS_EXCEPTION, "没有匹配到合适的商户信息",null);
                return;
            }

            dataMatchResult.setMatchOrderId(dataMatchOrderInfo.getId());
            dataMatchResult.setUid(memberSourceInfo.getUid());

            /**
             * 根据匹配结果，更新匹配订单信息
             */
            dataMatchOrderInfoService.saveMatchOrderResult(dataMatchResult, dataMatchOrderInfo, memberSourceInfo);

//        return new ResponseVo(AppRspCodeConstant.SUCCESS,"申请成功",null);
            return;
        }catch (Exception exception){
            exception.printStackTrace();
        }
    }

    // 查询订单信息
    // orderItem
    @Override
    public ResponseVo getApiBApproveUrlListResult(Long uid) {
        JSONObject jsonObject = new JSONObject();
        MemberSourceInfo memberSourceInfo = memberSourceInfoMapper.getEntityByUidLock(Long.valueOf(uid));
        if (ObjectUtil.isEmpty(memberSourceInfo)) {
            return new ResponseVo(AppRspCodeConstant.SYS_EXCEPTION, "用户信息为空",jsonObject);
        }

        List<DataMatchOrderItem> itemListByUidAndWaitPush = dataMatchOrderItemMapper.getItemListByUidAndWaitPush(uid);
        if (itemListByUidAndWaitPush.size() == 0){
            return new ResponseVo(AppRspCodeConstant.SYS_EXCEPTION, "无商户匹配的子订单项",jsonObject);
        }

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDateTime dateTime = LocalDateTime.now();
        String formattedDateTime = dateTime.format(formatter);
        String successNumberKey = StrUtil.format(RedisKeyConstant.MATCH_APIB_UIDS_LIST, formattedDateTime);

        // 先检查元素是否在 Redis List 中（保证唯一性）
        if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(successNumberKey))) {
            // 获取该 list 中的所有元素
            List<String> elements = stringRedisTemplate.opsForList().range(successNumberKey, 0, -1);

            // 如果元素不在 list 中，添加元素
            if (elements != null && !elements.contains(String.valueOf(uid))) {
                stringRedisTemplate.opsForList().rightPush(successNumberKey, String.valueOf(uid));
            }
        } else {
            // 如果该键不存在，创建 list 并添加元素
            stringRedisTemplate.opsForList().rightPush(successNumberKey, String.valueOf(uid));
            stringRedisTemplate.expire(successNumberKey, 7, TimeUnit.DAYS);
        }

        // 获取当前时间
        LocalDateTime currentTime = LocalDateTime.now();

        ArrayList<MerchantAbiBDataPushInfoVO> merchantAbiBDataPushInfoVOList = new ArrayList<>();
        itemListByUidAndWaitPush.stream().forEach(dataMatchOrderItem -> {
            // 计算两个时间之间的持续时间，判断超时
            Duration duration = Duration.between(dataMatchOrderItem.getTimeoutPeriod(), currentTime);
            if (Math.abs(duration.toMinutes()) <= 30) {
                Integer infoId = dataMatchOrderItem.getInfoId();
                MerchantBaseInfo merchantBaseInfo = merchantBaseInfoMapper.selectById(infoId);
                MerchantAbiBDataPushInfoVO merchantAbiBDataPushInfoVO = new MerchantAbiBDataPushInfoVO();
                merchantAbiBDataPushInfoVO.setApproveUrl(dataMatchOrderItem.getApproveUrl());
                merchantAbiBDataPushInfoVO.setOrderItemId(String.valueOf(dataMatchOrderItem.getId()));
                merchantAbiBDataPushInfoVO.setInfoId(String.valueOf(merchantBaseInfo.getId()));
                merchantAbiBDataPushInfoVO.setCompanyName(merchantBaseInfo.getCompanyName());
                merchantAbiBDataPushInfoVO.setCompanyLogo(merchantBaseInfo.getCompanyLogo());
                merchantAbiBDataPushInfoVO.setMaxLoanAmount(merchantBaseInfo.getMaxLoanAmount());
                merchantAbiBDataPushInfoVO.setMaxRate(merchantBaseInfo.getMaxRate());
                merchantAbiBDataPushInfoVO.setMinRate(merchantBaseInfo.getMinRate());
                merchantAbiBDataPushInfoVO.setStatus(true);

                merchantAbiBDataPushInfoVOList.add(merchantAbiBDataPushInfoVO);
            }
        });

        jsonObject.put("dataList",merchantAbiBDataPushInfoVOList);
        return new ResponseVo(AppRspCodeConstant.SUCCESS,"查询成功",jsonObject);
    }

    @Override
    public ResponseVo getApiBOrderItemClick(String orderItemId,String infoId) {
        DataMatchOrderItem entityByItemOrderIdAndInfoId = dataMatchOrderItemMapper.getEntityByItemOrderIdAndInfoId(Long.valueOf(orderItemId), Integer.valueOf(infoId));
        if (ObjectUtil.isEmpty(entityByItemOrderIdAndInfoId)) {
            return new ResponseVo(AppRspCodeConstant.SYS_EXCEPTION, "参数不正确");
        }
        DataMatchOrderItem dataMatchOrderItem = new DataMatchOrderItem();
        dataMatchOrderItem.setId(Long.valueOf(orderItemId));
        dataMatchOrderItem.setClickPushFlag(1);
        int i = dataMatchOrderItemMapper.updateById(dataMatchOrderItem);
        if (i != 1){
            return new ResponseVo(AppRspCodeConstant.SYS_EXCEPTION, "操作失败");
        }
        return new ResponseVo(AppRspCodeConstant.SUCCESS, "操作完成");
    }


}
